import {Form, Modal, Row, Col, Input, Select, InputNumber, Divider, message} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import AliyunOSSUpload from '@/components/AliyunOSSUpload/App';
import {normFile, uuid} from "@/utils/upload";

const DataForm = (props) => {
  const {dispatch, submitting, goodsList, goodsSpecList, serveList, serveCardList, pkgList, mchList} = props;
  const {
    dataForm, setDataForm, tablePayload, setTablePayload, selectedId
  } = props.data;
  const [form] = Form.useForm();
  const [img, setImg] = useState([]);
  const [type, setType] = useState(0);

  useEffect(() => {
    dispatch({type: 'MallCommon/fetchPkgList'});
    dispatch({type: 'MallCommon/fetchServeList'});
    dispatch({type: 'MallCommon/fetchGoodsList'});
    dispatch({type: 'MchCommon/fetchMchForIdList'});
  }, [dispatch]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({status: 1, orderby: 0});
    }
    if (dataForm && dataForm.parent) {
      form.setFieldsValue({pid: dataForm.parent.id});
    }
    if (dataForm && dataForm.data) {
      let {data} = dataForm;

      let img_ = [];
      if (dataForm.data.img) {
        img_ = [{uuid: uuid(), name: dataForm.data.img.split("/").pop(), status: 'done', url: dataForm.data.img}];
      }
      setImg(img_)

      form.setFieldsValue({
        ...data,
        img: img_
      });

      if (dataForm.data.type === 1) {
        dispatch({type: 'MallCommon/fetchGoodsSpecList', payload: {goodsId: dataForm.data.aboutId}});
      }
      if (dataForm.data.type === 2) {
        dispatch({type: 'MallCommon/fetchServeCardList', payload: {serveId: dataForm.data.aboutId}});
      }

      setType(dataForm.data.type);
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      values.pageId = selectedId;
      if (values.pageId <= 0) {
        message.error('请选择页面').then();
        return;
      }

      if (values.img && (values.img.length > 0)) {
        values.img = values.img.filter(d => d.status === 'done').pop().url;
      } else {
        values.img = '';
      }

      dispatch({
        type: values.id ? 'PCmsPageRight/edit' : 'PCmsPageRight/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
    setImg([]);
    setType(0);
  }

  /* 选中商品 */
  function onSelectGoods(e) {
    dispatch({type: 'MallCommon/fetchGoodsSpecList', payload: {goodsId: e}});
    form.setFieldsValue({subAboutId: undefined});
  }

  /* 选中服务 */
  function onSelectServe(e) {
    dispatch({type: 'MallCommon/fetchServeCardList', payload: {serveId: e}});
    form.setFieldsValue({subAboutId: undefined});
  }

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={900}
      bodyStyle={{paddingTop: 24, maxHeight: 500, overflowY: 'auto', overflowX: 'hidden'}}
    >
      <Form layout='horizontal' labelCol={{span: 3}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='type' label='类型'
              rules={[
                {required: true, message: '类型不能为空'},
              ]}
            >
              <Select placeholder='请选择类型' onSelect={e => setType(e)} disabled={dataForm && dataForm.data}>
                <Select.Option value={0}>常规</Select.Option>
                <Select.Option value={1}>商品</Select.Option>
                <Select.Option value={2}>服务</Select.Option>
                <Select.Option value={3}>套餐</Select.Option>
                <Select.Option value={4}>商家</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        {(type === 1) && (
          <>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='aboutId' label='商品名称'
                  rules={[
                    {required: true, message: '商品名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择商品名称' options={goodsList} allowClear showSearch onSelect={onSelectGoods}
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='subAboutId' label='商品规格'
                  rules={[
                    {required: true, message: '商品规格不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择商品规格' options={goodsSpecList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
          </>
        )}

        {(type === 2) && (
          <>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='aboutId' label='服务名称'
                  rules={[
                    {required: true, message: '服务名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择服务名称' options={serveList} allowClear showSearch onSelect={onSelectServe}
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='subAboutId' label='次卡名称'
                  rules={[
                    {required: true, message: '次卡名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择次卡名称' options={serveCardList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
          </>
        )}

        {(type === 3) && (
          <>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='aboutId' label='套餐名称'
                  rules={[
                    {required: true, message: '套餐名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择套餐名称' options={pkgList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
          </>
        )}

        {(type === 4) && (
          <>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  name='aboutId' label='商家名称'
                  rules={[
                    {required: true, message: '商家名称不能为空'},
                  ]}>
                  <Select
                    placeholder='请选择商家名称' options={mchList} allowClear showSearch
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  />
                </Form.Item>
              </Col>
            </Row>
          </>
        )}


        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='title' label='标题'
              rules={[
                {required: true, message: '标题不能为空'},
              ]}>
              <Input placeholder='请输入标题'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='url' label='跳转链接'
              rules={[
                {required: false, message: '跳转链接不能为空'},
              ]}>
              <Input placeholder='请输入跳转链接'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='intro' label='简介'
              rules={[
                {required: false, message: '简介不能为空'},
              ]}>
              <Input placeholder='请输入简介'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='orderby' label='排序属性'
              rules={[
                {required: true, message: '排序属性不能为空'},
              ]}>
              <InputNumber style={{width: '100%'}} placeholder='请输入排序属性'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='remark' label='备注信息'
              rules={[
                {required: false, message: '备注信息不能为空'},
              ]}
            >
              <Input placeholder='请输入备注信息'/>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{marginTop: 0}}/>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name={'img'}
              label="图片"
              rules={[
                {required: false, message: '图片不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{images: img, setImages: setImg, size: 10, len: 1, accept: 'image/*'}}/>
            </Form.Item>
          </Col>
        </Row>
        <Divider style={{marginTop: -12}}/>

      </Form>
    </Modal>
  );
};


export default connect(({loading, MallCommon, MchCommon}) => {
  return {
    submitting: loading.effects['PCmsPageRight/add'] || loading.effects['PCmsPageRight/edit'],
    goodsList: MallCommon.goodsList,
    goodsSpecList: MallCommon.goodsSpecList,
    serveList: MallCommon.serveList,
    serveCardList: MallCommon.serveCardList,
    pkgList: MallCommon.pkgList,
    mchList: MchCommon.mchList,
  };
})(DataForm);

